import { NextFunction, Request, Response } from 'express'
import logger from '../utils/logger'

export class AppError extends Error {
  statusCode: number
  status: string
  isOperational: boolean

  constructor(message: string, statusCode: number) {
    super(message)
    this.statusCode = statusCode
    this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'
    this.isOperational = true

    Error.captureStackTrace(this, this.constructor)
  }
}

interface ErrorResponse {
  status: string
  message: string
  code?: number
  path?: string
}

export const errorHandler = (
  err: AppError | Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const statusCode = 'statusCode' in err ? err.statusCode : 500
  const status = 'status' in err ? err.status : 'error'

  // 记录错误
  logger.error('Error:', {
    message: err.message,
    stack: err.stack,
    path: req.path,
    method: req.method,
    statusCode,
  })

  const response: ErrorResponse = {
    status,
    message: err.message,
  }

  // 监控错误
  if (req.path.startsWith('/api/monitor')) {
    response.code = statusCode
    response.path = req.path
  }

  res.status(statusCode).json(response)
}
